<template>
    <div class="merak-container-has-aside" curPageName="orgs123456789">
        <div class="merak-aside">
            <treeNode :defTreeValue="org_ids" @node-change="nodeChange"></treeNode>
        </div>

        <div v-waterMarker="{zIndex: 10}" class="merak-card merak-table-wrapper" v-loading="loading">
            <div class="right_content">
                <!-- exportImg downImg-->
                <div class="down_img" @click="exportImg" v-auth="{'authArr':authList,'key':'downImg'}">
                    <!-- <el-button type="default"> <el-icon>
                            <Download />
                        </el-icon>
                    </el-button> -->
                    <el-button :icon="Download" circle />
                </div>
                <organization-chart id="oragnizationPic" v-if="!loadingTree " class="oragnization_tree"
                    :class="{'bg_zh':$t('lang')=='zh'}" :exportButton="true" :datasource="orgDeep" :pan="true"
                    :zoom="true">
                    <template #default="slotProps">
                        <div
                            :class="{'node_level_one':(slotProps.nodeData.level==0),'node_level_two':(slotProps.nodeData.level==1),'node_level_three':(slotProps.nodeData.level==2),'node_level_four':(slotProps.nodeData.level==3)}">
                            <div class="node_bg_one">
                                <el-icon :size="12">
                                    <UserFilled />
                                </el-icon>
                                <span style="font-size: 12px;">{{ slotProps.nodeData.count }}</span>
                            </div>
                            <!-- 俄文展示 -->
                            <div class="node_bg_two" v-if="$t('lang')=='ru'">
                                {{ slotProps.nodeData.title }}
                            </div>

                            <!-- 中文展示 -->
                            <div class="node_bg_two node_bg_two_zh" v-else>

                                <!-- v-if="slotProps.nodeData.level==2||slotProps.nodeData.level==3" -->
                                <template v-if=" slotProps.nodeData.level==3">
                                    <div class="node_bg_one_test">
                                        {{ slotProps.nodeData.title }}
                                    </div>
                                    <div class="node_bg_two_test" v-html="roateTxt(slotProps.nodeData.title)">
                                    </div>
                                </template>

                                <template v-else>
                                    {{ slotProps.nodeData.title }}
                                </template>

                            </div>
                        </div>

                    </template>
                </organization-chart>
            </div>

        </div>
    </div>
</template>
<script setup lang="ts">
    import { Download } from '@element-plus/icons-vue'
    import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
    import { ref, reactive, toRefs, onMounted, computed, nextTick } from 'vue';
    import OrganizationChart from 'vue3-organization-chart'
    import 'vue3-organization-chart/dist/orgchart.css';
    import html2canvas from "html2canvas";
    import { getLocationParams } from "@/utils/index";
    import { useGlobalStore } from "@/stores/modules/global";
    import { getOrgsMapApi } from "@/api/modules/personalManagementApi/organization";


    import { useDefaultStore } from '@/stores/modules/default';
    import { toPng } from 'html-to-image';
    import { exportTableApi } from "@/api/modules/table";
    const defaultStore = useDefaultStore();
    const globalStore = useGlobalStore();
    // 权限参数
    const authList = reactive({});
    const rawHtml = ref('<p>这是<b>HTML</b>内容</p>');
    const org_ids = ref(0);
    //接收url参数
    const newUrl = new URL(window.location.href);
    let url_org_id = getLocationParams(newUrl.href, 'org_id');
    org_ids.value = url_org_id;

    // 树结构选择
    const nodeChange = (data: any) => {
        console.log(data, "树节点值，，，，")
        let { org_id } = data;

        // 构建新的URL
        const newUrl = new URL(window.location.href);
        newUrl.searchParams.set('org_id', org_id);
        // org_id.value= org_id;
        // 使用pushState更新浏览器历史记录
        window.history.pushState({}, '', newUrl.toString());


        getOrgsMap({ org_id: org_id })
    }


    const loading = ref(false);
    const loadingTree = ref(false);
    let orgDeep = reactive({});
    //获取组织架构图
    const getOrgsMap = (params) => {
        loading.value = true;
        loadingTree.value = true;
        let { org_id = 0 } = params;
        getOrgsMapApi({ org_id: org_id }).then(res => {
            console.log(res, "=======================")
            loading.value = false;
            loadingTree.value = false;
            //权限
            if (res.auth_list) {
                let authListTwo = res.auth_list;
                Object.assign(authList, authListTwo);
            }

            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data;
                if (data && !data.children) {
                    data.children = []
                }
                Object.assign(orgDeep, data);

                nextTick(() => {
                    // 
                    if (globalStore.language == 'zh') {
                        sumLayouthei()
                    }
                })
            } else {
                failMsg(res.message)
            }
        })
    }
    //中文下计算高度
    const sumLayouthei = () => {
        let zhDom = document.getElementsByClassName("node_bg_two_test");
        let zhOneDom = document.getElementsByClassName("node_bg_one_test");
        for (let zhIndex = 0; zhIndex < zhDom.length; zhIndex++) {
            let hei = zhDom[zhIndex].getBoundingClientRect().height;
            zhOneDom[zhIndex].style.cssText = `height:${hei}px`;
        }
    }
    onMounted(() => {
        getOrgsMap({ org_id: org_ids.value || 0 })
    })

    const roateTxt = (text) => {
        // 正则表达式匹配中文字符
        const regex = /[\u4e00-\u9fa5]/g;
        // 使用replace方法替换并添加div标签
        return text.replace(regex, function (match) {
            return `<div class='roate_zh'>${match}</div>`;
        });
    }



    // 导出
    const exportImg333 = () => {
        loading.value = true;
        const node = document.querySelector('.table');
        console.log(node)
        setTimeout(() => {
            toPng(node).then((dataUrl) => {
                // 使用图片数据URL
                console.log(dataUrl);
                // this.imgUrl = dataUrl
                exportTableApi({ file: dataUrl, route_name: new Date().getTime() }).then(res => {
                    if (res.code == ResultEnum.SUCCESS) {
                        loading.value = false;
                        defaultStore.downVisable = true; //打开下载列表
                    }
                }).catch(() => {
                    loading.value = false;
                });

            })
                .catch(function (error) {
                    console.error('转换错误:', error);
                });
        }, 80);

    }




    //下载
    // 绑定  需要把那个内容生成图 
    const currentImg = ref('');
    const show = ref(false);
    const exportImg = async () => {
        loading.value = true;
        // const el = document.getElementById(`oragnizationPic`) 
        const el = document.getElementsByClassName('chartOrgchart');
        const el2 = document.getElementsByClassName('chartOrgchart')[0].children;
        console.log('el:', el)
        let hei1 = window.getComputedStyle(el[0]).height;
        let hei2 = window.getComputedStyle(el2[0]).height;
        // const canvasFalse = document.createElement('canvas')
        const width = parseInt(window.getComputedStyle(el[0]).width)
        const height = parseInt((hei1 > hei2 ? hei1 : hei2))
        console.log('width:', width, 'height:', height)
        let canvas = await autoPicture({ width, height });
        console.log(new Date(), "导出图片11111111")
        if (canvas) {
            currentImg.value = canvas
            show.value = true;
            // canvas为转换后的Canvas对象
            let oImg = new Image()
            oImg = currentImg.value;// 导出图片
            // console.log(oImg)
            // console.log(new Date(), "导出图片22222222")
            // var oA = document.createElement('a')
            // oA.download = new Date().getTime(); // 设置下载的文件名，默认是'下载'
            // oA.href = oImg
            // document.body.appendChild(oA)
            // oA.click()
            // console.log(new Date(), "导出图片3333333")

            // oA.remove() // 下载之后把创建的元素删除



            exportTableApi({ file: oImg, route_name: new Date().getTime() }).then(res => {
                if (res.code == ResultEnum.SUCCESS) {
                    loading.value = false;
                    defaultStore.downVisable = true; //打开下载列表
                }
            }).catch(() => {
                loading.value = false;
            });
        }

    }





    const autoPicture = async (options) => {
        let { scale = 1, allowTaint = false, useCORS = true, width = '375', height = '649', backgroundColor = null } = options;
        let orgChart = document.querySelector(".chartOrgchart");
        const canvas = await html2canvas(orgChart, {
            scale: 2, //缩放比例,默认为1 
            dpi: 300, // 处理模糊问题
            backgroundColor: '#ffffff',//海报的背景颜色
            allowTaint, //是否允许跨域图像污染画布
            useCORS, //是否尝试使用CORS从服务器加载图像
            width, //画布的宽度
            height, //画布的高度 
        })
        return canvas.toDataURL('image/png')
    }


</script>

<style lang="scss">
    @import "./index.scss";
</style>